from django.shortcuts import HttpResponse
from django.db import connection
from .models import Book, Tag
# Create your views here.
def index(request):
    with connection.cursor() as cursor:
        cursor.execute("select * from book")
        books = cursor.fetchall()
    # return render(request, 'book/index.html', {'books': books})
        for book in books:
            print(book)
        return HttpResponse("ok")
# 在数据库中增加数据
def add_book(request):
    # book = Book(title='大奉打更人',author='卖报小郎据',price=100)
    # book.save()
    book = Book(title='庆余年', author='上善如水',price=101)
    book.save()
    return HttpResponse("ok")
# 在数据库中查找数据
def find_book(request):
    books = Book.objects.all()
    for book in books:
        print(book.title, book.author, book.pub_time, book.price)
    return HttpResponse("ok")
# 数据过滤
def filter_book(request):
    books = Book.objects.filter(title='大奉打更人')
    for book in books:
        print(book.title, book.author, book.pub_time, book.price)
    return HttpResponse("ok")
# 获取单个对象
def get_book(request):
    books = Book.objects.get(title='大奉打更人')
    # for book in books:
    print(books.author, books.price,books.pub_time)
    return HttpResponse("ok")
    # try:
    #     books = Book.objects.get(title='大奉打更人11')
    # except:
    #     return HttpResponse("图书不存在")
# 数据排序
def order_book(request):
    # 以价格排序从小到大,默认是从小到大,在前面加负号，从大到小
    # books = Book.objects.order_by('-price')
    books = Book.objects.all()
    for book in books:
        print(book.title, book.author, book.pub_time, book.price)
    return HttpResponse("ok")
# 修改数据
def update_book(request):
    # books = Book.objects.get(title='大奉打更人')
    # books.price = 99
    # books.save()
    # return HttpResponse("ok")
    books = Book.objects.first()
    books.price = 102
    books.save()
    return HttpResponse("ok")
# 删除数据
def delete_book(request):
    books = Book.objects.filter(title='庆余年')
    books.delete()
    return HttpResponse("ok")
def book_tag(request):
    tag = Tag()
    tag.save()
    return HttpResponse("ok")